//
//  BIDLoginViewController.m
//  EducationAssistant
//
//  Created by mal on 15/6/2.
//  Copyright (c) 2015年 cnsoft. All rights reserved.
//

#import "BIDLoginViewController.h"
#import "BIDGlobalMethods.h"
#import "BIDManageViewController.h"
#import "UIView+FindFirstResponder.h"
#import "BIDDatabaseManager.h"
#import "BIDCustomTextField.h"

#import "BIDRegisterViewController.h"
#import "BIDResetPasswordFirstStepViewController.h"

//登录
static NSString *loginURL = @"mobile/login.action";


@interface BIDLoginViewController ()
{
    UIImageView *_imgViewForAccount;
    UIImageView *_imgViewForPwd;
}

@end

@implementation BIDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    _containerView.clipsToBounds = YES;
    _containerView.layer.cornerRadius = 3.f;
    _containerView.layer.borderColor = RGBACOLOR(237, 239, 240, 1.f).CGColor;
    _containerView.layer.borderWidth = 1.f;
    [self prepareForLayout];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *初始化界面
 */
- (void)prepareForLayout
{
    self.navigationController.navigationBarHidden = YES;
    //
    _usernameTF.inputAccessoryView = self.toolBar;
    _passwordTF.inputAccessoryView = self.toolBar;
    //
    UIImageView *imgView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_username.png"]];
    UIImageView *imgView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_password.png"]];
    _usernameTF.leftView = imgView1;
    _usernameTF.leftViewMode = UITextFieldViewModeAlways;
    _passwordTF.leftView = imgView2;
    _passwordTF.leftViewMode = UITextFieldViewModeAlways;    
    //设置按钮背景
    [BIDGlobalMethods setImgForBtn:_loginBtn imgNameForNormal:@"loginBtnBg_normal.png" imgNameForHighlight:@"loginBtnBg_select.png"];
    _loginBtn.clipsToBounds = YES;
    _loginBtn.layer.cornerRadius = 3.f;
    //add tapGesture for view
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    tapGR.numberOfTapsRequired = 1;
    tapGR.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tapGR];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    //填充用户名
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *strUsername = [userDefaults objectForKey:@"username"];
    if(strUsername.length>0)
    {
        _usernameTF.text = strUsername;
    }
}

- (IBAction)textFieldEditBeginHandler:(id)sender
{
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    
    //NSValue *durationValue = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *firstResponderView = [keyWindow findFirstResponder];
    
    CGFloat containerViewY = 181.f;
    
    if(firstResponderView.frame.origin.y + firstResponderView.frame.size.height + containerViewY > (self.view.frame.size.height-(self.keyboardHeight-self.distanceToMove)))
    {
        //NSTimeInterval timeInterval;
        //[durationValue getValue:&timeInterval];
        [UIView beginAnimations:@"animation" context:nil];
        [UIView setAnimationDuration:0.25f];
        CGRect frame = self.view.frame;
        
        int moveLen = containerViewY + firstResponderView.frame.origin.y + firstResponderView.frame.size.height - (self.view.frame.size.height-(self.keyboardHeight-self.distanceToMove));
        self.distanceToMove += moveLen;
        frame.origin.y -= moveLen;
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

/**
 *登录
 */
- (IBAction)loginBtnHandler:(id)sender
{
    [_usernameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
    NSString *strUsername = _usernameTF.text;
    NSString *strPassword = _passwordTF.text;
    if(strUsername.length==0 || strPassword.length==0)
    {
        //用户名和密码不能为空
        [self showAlertView:@"用户名和密码不能为空" buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
        return;
    }
    [self loginOwnPlatformWithUsername:strUsername password:strPassword];
}
/**
 *登录本平台
 */
- (void)loginOwnPlatformWithUsername:(NSString*)strUsername password:(NSString*)strPassword
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], loginURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"member.userName=%@&member.password=%@", strUsername, strPassword];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            //有错误信息
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:@""];
        }
        else if(responseDic)
        {
            //登录成功，保存用户名和密码
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            
            [userDefaults setObject:strUsername forKey:@"username"];
            [userDefaults setObject:strPassword forKey:@"password"];
            
            [userDefaults synchronize];
            //
            NSDictionary *subDic = responseDic[@"member"];
            //保存userId
            NSString *strUserId = subDic[@"id"];
            [AppDelegate setUserId:strUserId];
            [AppDelegate setUserTrueName:subDic[@"trueName"]];
            [AppDelegate setUserName:subDic[@"userName"]];
            [AppDelegate setUserDetailInfo:responseDic[@"memberDetail"]];
            //获取用户绑定的房屋列表
            [self fetchBindingHouse];
            //
            BIDManageViewController *manageVC = [[BIDManageViewController alloc] initWithNibName:@"BIDManageViewController" bundle:nil];
            [self.navigationController setViewControllers:@[manageVC] animated:YES];
        }
    }];
}

/**
 注册

 @param sender <#sender description#>
 */
- (IBAction)registerBtnHandler:(id)sender
{
    BIDRegisterViewController *vc = [[BIDRegisterViewController alloc] initWithNibName:@"BIDRegisterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 忘记密码/重置密码

 @param sender <#sender description#>
 */
- (IBAction)resetPasswordBtnHandler:(id)sender
{
    BIDResetPasswordFirstStepViewController *vc = [[BIDResetPasswordFirstStepViewController alloc] initWithNibName:@"BIDResetPasswordFirstStepViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 获取当前用户已绑定的房屋列表
 */
- (void)fetchBindingHouse
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], @"memberHouseAndroid/list.action"];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@", [AppDelegate getUserId]];
    id obj = [BIDDataCommunication getDataFromNetBySyn:strRequestURL postValue:strPost];
    if(obj && [obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if([value intValue] == 1)
        {
            [AppDelegate setBindingHouse:dic[@"body"][@"rows"]];
        }
    }
}

/**
 提示框的相应处理

 @param obj <#obj description#>
 */
- (void)alertViewHandler:(id)obj
{
    obj = (NSNumber *)obj;
    if([obj unsignedIntegerValue] == 1)
    {
        NSArray *vcArr = [self.navigationController viewControllers];
        for(UIViewController *vc in vcArr)
        {
            if([vc isKindOfClass:[BIDLoginViewController class]])
            {
                [self.navigationController popToViewController:vc animated:YES];
                break;
            }
        }
    }
}

/**
 *
 */
- (void)tapGestureHandler:(UIGestureRecognizer*)gr
{
    [_usernameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
}
/**
 *
 */
- (IBAction)textFieldEditDone:(id)sender
{
    [_usernameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
}

@end
